"""add diary comments and anniversary extensions

Revision ID: 202510170001
Revises: 202502100001
Create Date: 2025-10-17 18:40:00
"""

from alembic import op
import sqlalchemy as sa


revision = "202510170001"
down_revision = "202502100001"
branch_labels = None
depends_on = None


def upgrade() -> None:
  # Create diary_comments table
  op.create_table(
    "diary_comments",
    sa.Column("id", sa.Integer(), primary_key=True, index=True),
    sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
    sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
    sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
    sa.Column("diary_entry_id", sa.Integer(), nullable=False),
    sa.Column("user_id", sa.Integer(), nullable=False),
    sa.Column("content", sa.Text(), nullable=False),
    sa.Column("mood", sa.String(length=64), nullable=True),
    sa.ForeignKeyConstraint(["diary_entry_id"], ["diary_entries.id"], ondelete="CASCADE"),
    sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
  )
  op.create_index("ix_diary_comments_entry_id", "diary_comments", ["diary_entry_id"], unique=False)
  op.create_index("ix_diary_comments_user_id", "diary_comments", ["user_id"], unique=False)

  # Extend anniversaries
  countdown_mode_enum = sa.Enum("down", "up", "both", name="anniversary_countdown_mode")
  countdown_mode_enum.create(op.get_bind(), checkfirst=True)

  op.add_column("anniversaries", sa.Column("is_lunar", sa.Boolean(), nullable=False, server_default=sa.text("0")))
  op.add_column("anniversaries", sa.Column("lunar_date_str", sa.String(length=16), nullable=True))
  op.add_column(
    "anniversaries",
    sa.Column("countdown_mode", countdown_mode_enum, nullable=False, server_default="down"),
  )


def downgrade() -> None:
  op.drop_column("anniversaries", "countdown_mode")
  op.drop_column("anniversaries", "lunar_date_str")
  op.drop_column("anniversaries", "is_lunar")
  # Drop enum if exists
  try:
    sa.Enum(name="anniversary_countdown_mode").drop(op.get_bind(), checkfirst=True)
  except Exception:  # pragma: no cover
    pass

  op.drop_index("ix_diary_comments_user_id", table_name="diary_comments")
  op.drop_index("ix_diary_comments_entry_id", table_name="diary_comments")
  op.drop_table("diary_comments")

